<template>
  <div class="suplus">
    <div class="suplus-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-storageadd'"
            @click="showEditDialog('add')"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button v-btnpermission="'btn-storageload'" type="primary"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="所属城市" prop="cityCode">
            <el-tree-select
              v-model="formSearch.cityCode"
              :data="cityTreeOption"
              :props="defaultProps"
              :render-after-expand="false"
              node-key="Code"
              check-strictly
              @change="cs11"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.activityvenuescode"
              placeholder="--选择--"
              filterable
              clearable
              @change="csVenuesChange"
            >
              <el-option
                v-for="item in activityVenuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属仓库">
            <el-cascader
              v-model="formSearch.MedicalPoint"
              :options="medicalPointOption"
              :props="{
                checkStrictly: true,
              }"
              clearable
            />
            <!-- <el-select v-model="formSearch.MedicalPoint" placeholder="--选择--">
              <el-option
                v-for="item in medicalPointOption"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item label="名称" prop="Name">
            <el-input
              v-model="formSearch.Name"
              placeholder="请输入搜索名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="classType">
            <el-select
              v-model="formSearch.classType"
              placeholder="分类"
              clearable
              filterable
            >
              <el-option
                v-for="item in classOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="suplus-list">
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="DictionaryList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <!-- <el-table-column prop="Code" label="编码"></el-table-column> -->
            <el-table-column prop="DAC_Name" label="名称"></el-table-column>
            <el-table-column prop="Remainder" label="剩余"></el-table-column>
            <el-table-column
              prop="MedicalPointName"
              label="所属仓库"
            ></el-table-column>
            <el-table-column prop="Total" label="总数"> </el-table-column>
            <el-table-column prop="WarningValue" label="警戒值">
            </el-table-column>

            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-storageupdate'"
                  :icon="Edit"
                  @click="showEditDialog('edit', scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-storagedelete'"
                  @click="rowDelete(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        :title="titleref"
        v-model="addDialogVisible"
        width="40%"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogForm"
          :rules="surplusFormRulesMixin.addFormRules"
          ref="addDialogRef"
          label-width="80px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="所属城市" prop="cityCode">
                <el-tree-select
                  v-model="addDialogForm.cityCode"
                  :data="cityTreeOptionAdd"
                  :props="defaultProps"
                  :render-after-expand="false"
                  node-key="Code"
                  check-strictly
                  filterable
                  @change="cs11Add"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="场馆" prop="activityvenuescode">
                <el-select
                  v-model="addDialogForm.activityvenuescode"
                  placeholder="--选择--"
                  filterable
                  @change="csVenuesChangeAdd"
                  clearable
                >
                  <el-option
                    v-for="item in activityVenuesOptionAdd"
                    :key="item.Code"
                    :label="item.CHIDescription"
                    :value="item.Code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="选择仓库" prop="MedicalPointCode">
                <el-cascader
                  v-model="addDialogForm.MedicalPointCode"
                  :options="medicalPointOptionAdd"
                  :props="{
                    checkStrictly: false,
                  }"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="药品名称" prop="DAC_Code">
                <el-select
                  v-model="addDialogForm.DAC_Code"
                  placeholder="--选择--"
                  clearable
                  filterable
                >
                  <el-option-group
                    v-for="group in dicDrugsOption"
                    :key="group.value"
                    :label="group.label"
                    style="color: red"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                      <el-row>
                        <el-col :span="12">
                          {{ item.label }}
                        </el-col>
                        <el-col :span="3">
                          {{ item.unit }}
                        </el-col>
                        <el-col :span="8">
                          {{ item.specifications }}
                        </el-col>
                      </el-row>
                    </el-option>
                  </el-option-group>
                </el-select>
              </el-form-item></el-col
            >
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="Remainder" label="剩余">
                <el-input-number v-model="addDialogForm.Remainder" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="总数" prop="Total">
                <el-input-number v-model="addDialogForm.Total">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="WarningValue" label="警戒值">
                <el-input-number v-model="addDialogForm.WarningValue" />
              </el-form-item>
            </el-col>
            <el-col :span="10"> </el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { surplusFormRulesMixin } from '@/utils/mixin';
import { importExcel } from '@/utils/excel';
import {
  getSurplusList,
  addSurplus,
  editSurplus,
  delSurplus,
  addSurplusList,
  getDrugsSortedGroup,
} from '@/network/suplus.js';
import {
  getDicByTagType,
  getCityTree,
  getActivityVenues,
} from '@/network/dictionary';
const cityTreeOption = ref(null);
const cityTreeOptionAdd = ref(null);
const cityTreeOptionUpdate = ref(null);
const activityVenuesOption = ref(null);
const activityVenuesOptionAdd = ref(null);
const activityVenuesOptionUpdate = ref(null);
const classOptions = ref([
  {
    label: '药品',
    value: 1,
  },
  {
    label: '耗材',
    value: 2,
  },
  {
    label: '设备',
    value: 3,
  },
]);
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const titleref = ref('');
const showEditDialog = (type, row) => {
  titleref.value = type == 'add' ? '新增' : '修改';
  addDialogVisible.value = true;
  let rdata = JSON.parse(JSON.stringify(row)); //深拷贝
  rdata.MedicalPointCode = rdata.MedicalPointCode.split(',');
  addDialogForm.value = type == 'add' ? {} : rdata;
};
let venuesOptionArray = [];
let medicalPointArray = [];
const cs11 = async (val) => {
  //场馆赋值
  activityVenuesOption.value = venuesOptionArray.filter(
    (it) => it.CityCode == val,
  );
  //清空
  formSearch.value.activityvenuescode = null;
  formSearch.value.MedicalPoint = null;
  //联动
  let arrayfilter = [];
  medicalPointArray.forEach((v, i) => {
    let obj = {};
    obj.label = v.label;
    obj.value = v.value;
    if (Array.isArray(v.children)) {
      let yy = Array.from(v.children);
      obj.children = yy.filter((it) => {
        if (val) {
          return it.citycode == val;
        }
        return true;
      });
    }
    arrayfilter.push(obj);
  });
  medicalPointOption.value = arrayfilter;
};
const cs11Add = async (val) => {
  //赋值
  activityVenuesOption.value = venuesOptionArray.filter(
    (it) => it.CityCode == val,
  );
  //清空
  addDialogForm.value.activityvenuescode = null;
  addDialogForm.value.MedicalPointCode = null;
  //联动
  //进行过滤---不从后台取值，直接过滤
  let arrayfilter = [];
  medicalPointArray.forEach((v, i) => {
    let obj = {};
    obj.label = v.label;
    obj.value = v.value;
    if (Array.isArray(v.children)) {
      let yy = Array.from(v.children);
      obj.children = yy.filter((it) => {
        if (val) {
          return it.citycode == val;
        }
        return true;
      });
    }
    arrayfilter.push(obj);
  });
  medicalPointOptionAdd.value = arrayfilter;
};
const csVenuesChange = async (val) => {
  //清空
  formSearch.value.MedicalPoint = null;
  //联动
  //进行过滤---不从后台取值，直接过滤
  let arrayfilter = [];
  medicalPointArray.forEach((v, i) => {
    let obj = {};
    obj.label = v.label;
    obj.value = v.value;
    if (Array.isArray(v.children)) {
      obj.children = Array.prototype.filter.call(v.children, (it) => {
        if (val && formSearch.value.cityCode) {
          return (
            it.venuescode == val && it.citycode == formSearch.value.cityCode
          );
        } else if (val) {
          return it.venuescode == val;
        } else if (formSearch.value.cityCode) {
          return it.citycode == formSearch.value.cityCode;
        }
      });
    }
    arrayfilter.push(obj);
  });
  medicalPointOption.value = arrayfilter;
};
const csVenuesChangeAdd = async (val) => {
  //清空
  addDialogForm.value.MedicalPoint = null;
  //联动
  //进行过滤---不从后台取值，直接过滤
  let arrayfilter = [];
  medicalPointArray.forEach((v, i) => {
    let obj = {};
    obj.label = v.label;
    obj.value = v.value;
    if (Array.isArray(v.children)) {
      obj.children = Array.prototype.filter.call(v.children, (it) => {
        if (val && addDialogForm.value.cityCode) {
          return (
            it.venuescode == val && it.citycode == addDialogForm.value.cityCode
          );
        } else if (val) {
          return it.venuescode == val;
        } else if (addDialogForm.value.cityCode) {
          return it.citycode == addDialogForm.value.cityCode;
        }
      });
    }
    arrayfilter.push(obj);
  });
  medicalPointOptionAdd.value = arrayfilter;
};
//搜索
const formSearch = ref({
  cityCode: null,
  activityvenuescode: null,
  Name: '',
  MedicalPoint: [],
  total: 0,
  page: 1,
  pageSize: 10,
  classType: null,
});
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.value.page - 1) * formSearch.value.pageSize + 1;
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addSurplusList(res).then(() => {
        ElMessage.success('导入成功');
        initDict();
        initData();
      });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};

//初始化数据
const DictionaryList = ref([]);
const dicDrugsOption = ref([]);
const initData = () => {
  let params = {
    page: formSearch.value.page,
    pageSize: formSearch.value.pageSize,
    Name: formSearch.value.Name,
    MedicalPoint: formSearch.value.MedicalPoint,
    cityCode: formSearch.value.cityCode,
    activityvenuescode: formSearch.value.activityvenuescode,
    classType: formSearch.value.classType,
  };
  getSurplusList(params).then((res) => {
    DictionaryList.value = res.data;
    formSearch.value.total = res.total;
  });
};
//初始化字典
const medicalPointOption = ref([]);
const medicalPointOptionAdd = ref([]);
const medicalPointOptionUpdate = ref([]);
const initDict = async () => {
  //医疗点
  await getDicByTagType().then((res) => {
    medicalPointOption.value = res;
    medicalPointOptionAdd.value = res;
    medicalPointOptionUpdate.value = res;
    medicalPointArray = res;
  });
  //获取药品字典
  await getDrugsSortedGroup().then((res) => {
    dicDrugsOption.value = res;
  });
  //获取城市
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
    cityTreeOptionAdd.value = res;
    cityTreeOptionUpdate.value = res;
  });
  await getActivityVenues().then((res) => {
    venuesOptionArray = res;
    activityVenuesOption.value = res;
    activityVenuesOptionAdd.value = res;
    activityVenuesOptionUpdate.value = res;
  });
};
onBeforeMount(() => {
  initData();
  initDict();
});
//搜索
const onSubmit = () => {
  formSearch.value.page = 1;
  initData();
};
//重置
const onReset = () => {
  formSearch.value.Name = '';
  formSearch.value.MedicalPoint = '';

  formSearch.value.page = 1;
  initData();
};
//分页
const handleCurrentChange = (val) => {
  formSearch.value.page = val;
  initData();
};
//新增
const addDialogVisible = ref(false);
const addDialogRef = ref(null);
const addDialogForm = ref({
  Code: 0,
  DAC_Code: null,
  Remainder: 0,
  MedicalPointCode: [],
  Total: 0,
  WarngingValue: null,
  cityCode: null,
  activityvenuescode: null,
});
const addFormSubmit = async () => {
  await addDialogRef.value.validate(async (valid) => {
    if (valid) {
      addDialogForm.value.MedicalPointCode =
        addDialogForm.value.MedicalPointCode[1];
      if (titleref.value == '新增') {
        await addSurplus(addDialogForm.value)
          .then(() => {
            addDialogVisible.value = false;
            initData();
            // initDict();
            ElMessage.success('新增成功');
          })
          .catch((err) => {
            console.log(err);
            ElMessage.error('新增失败！');
          });
      } else {
        await editSurplus(addDialogForm.value)
          .then(() => {
            addDialogVisible.value = false;
            initData();
            // initDict();
            ElMessage.success('修改成功');
          })
          .catch((err) => {
            console.log(err);
            ElMessage.error('修改失败！');
          });
      }
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
const addDislogClosed = () => {
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};

//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await delSurplus({ code: id })
        .then(() => {
          initData();
          // initDict();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
</script>

<style lang="scss" scoped>
.suplus {
  margin: 14px 15px 14px;
  .suplus-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .suplus-list {
    margin-top: 14px;
  }
}
:deep(.el-select-group__title) {
  font-size: 16px;
  color: rgb(75, 14, 243);
}
</style>
